//
//  OAuthViewController.swift
//  GbSinaBlog
//
//  Created by gongtao on 15/3/8.
//  Copyright (c) 2015年 _organizeation. All rights reserved.
//

import UIKit

class OAuthViewController: UIViewController {
    
    let WB_API_URL_String      = "https://api.weibo.com"
    let WB_Redirect_URL_String = "http://www.itheima.com"
    let WB_Client_ID           = "2720451414"
    let WB_Client_Secret       = "e061ff9a264a0bedb55226685b34c084"
    let WB_Grant_Type          = "authorization_code"
        
    @IBOutlet var webView: UIWebView!
    
    
    override func viewDidLoad() {
        super.viewDidLoad()
        loadOAuthPage()
    }
    
    //加载授权页面
    func loadOAuthPage() {
        let urlString = "https://api.weibo.com/oauth2/authorize?client_id=2720451414&redirect_uri=http://www.itheima.com"
        let url = NSURL(string: urlString)
        webView.loadRequest(NSURLRequest(URL: url!))
    }
}

extension OAuthViewController: UIWebViewDelegate {
    //页面重定向
    func webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool {
        
        let result = continueAndCode(request.URL!)
        //拼接参数字典
        if let code = result.code {
            let params = [
                "client_id": WB_Client_ID,
                "client_secret": WB_Client_Secret,
                "grand_type": WB_Grant_Type,
                "redirect_url": WB_Redirect_URL_String,
                "code": code]
            
            let net = NetworkManager.shareManager
            net.requestJSON(.POST, "https://api.weibo.com/oauth2/access_token", params, completion: { (result, error) -> () in
                println(result)
            })
        }
        
        if !result.continuePerform {
            println("拒绝加载,不行,再次加载!")
            loadOAuthPage()
        }
    
        return result.continuePerform
    }
    
    ///  传入URL确定是否继续执行和授权code
    ///
    ///  :param: url 执行URL
    ///
    ///  :returns: 是否继续执行/授权代码的元组
    func continueAndCode(url:NSURL) -> (continuePerform:Bool, code:String?) {
        let urlString = url.absoluteString!
        if !urlString.hasPrefix(WB_API_URL_String) {
            if urlString.hasPrefix(WB_Redirect_URL_String) {
                if let query = url.query {
                    let codestr:NSString = "code="
                    if query.hasPrefix(codestr as String) {
                        var q = query as NSString!
                        return (false, q.substringFromIndex(codestr.length))
                    }
                }
            }
            return (false, nil)
        }
        return (true, nil)
    }
}
